import { useState, useEffect, useRef } from "react";
import type { FC } from "react";
import MarkdownRenderer from "./MarkdownRenderer";
import type { ChatMessage } from "../types/chat";
import TypewriterEffect from "./TypewriterEffect";
import ImagePreview from "./ImagePreview";

interface MessageContentProps {
  /** 消息对象 */
  message: ChatMessage;
  /** 是否允许渲染HTML，默认为false */
  allowHtml?: boolean;
  /** 是否正在流式接收中 */
  isStreaming?: boolean;
}

/**
 * 消息内容组件
 *
 * 负责渲染消息内容，支持Markdown格式和图片显示
 * 根据消息类型（用户/助手）应用不同的样式
 * 使用打字机效果显示AI的回复内容
 */
const MessageContent: FC<MessageContentProps> = ({
  message,
  allowHtml = false,
  isStreaming = false,
}) => {
  // 判断是否有图片
  const hasImage = !!message.imageUrl;

  // 判断是否有上传文件
  const hasUploadFiles = message.files && message.files.length > 0;

  // 是否是占位符消息（用于特殊处理）
  const isPlaceholder = !!message.isPlaceholder;

  // 处理后的消息内容
  const [processedContent, setProcessedContent] = useState<string>(
    message.content || ""
  );

  // 图片预览状态
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);

  // 直接渲染的图片列表（从Markdown提取）
  const [extractedImages, setExtractedImages] = useState<
    { url: string; alt: string }[]
  >([]);

  // 用于跟踪是否已经进行了处理，防止无限循环
  const processedRef = useRef(false);

  // 识别并提取出图片链接
  const extractImageLinks = (
    content: string
  ): {
    extractedImages: { url: string; alt: string }[];
    newContent: string;
  } => {
    // 如果没有可能的图片标记，则直接返回原内容
    if (!content.includes("![") || !content.includes("](")) {
      return { extractedImages: [], newContent: content };
    }

    const images: { url: string; alt: string }[] = [];

    // 基本的Markdown图片语法: ![alt](url)
    const basicImageRegex = /!\[(.*?)\]\((https?:\/\/[^)]+)\)/g;
    let match;
    let newContent = content;

    // 找出所有符合Markdown图片语法的内容
    while ((match = basicImageRegex.exec(content)) !== null) {
      const fullMatch = match[0];
      const alt = match[1] || "file";
      const url = match[2];

      // 添加到提取列表
      images.push({ url, alt });

      // 如果图片链接是消息的主要内容，从文本内容中移除它
      if (
        content.trim() === fullMatch.trim() ||
        content.trim().startsWith(fullMatch.trim())
      ) {
        // 如果只有图片链接，或者图片链接在消息开头
        newContent = newContent.replace(fullMatch, "").trim();
      }
    }

    // 处理特殊格式的图片链接，例如在文本中间的链接
    if (images.length === 0) {
      // 尝试查找任何URL格式的内容
      const urlRegex = /(https?:\/\/[^\s]+\.(jpg|jpeg|png|gif|webp))/g;
      while ((match = urlRegex.exec(content)) !== null) {
        const url = match[1];
        images.push({ url, alt: "image" });
      }
    }

    return { extractedImages: images, newContent };
  };

  // 处理消息内容中的Markdown图片语法
  useEffect(() => {
    if (!message.content || processedRef.current) return;

    // 防止重复处理
    processedRef.current = true;

    // 提取图片链接和处理后的内容
    const { extractedImages: images, newContent } = extractImageLinks(
      message.content
    );

    // 如果找到图片链接
    if (images.length > 0) {
      setExtractedImages(images);

      // 如果有剩余内容，作为文本显示
      if (newContent.trim()) {
        setProcessedContent(newContent);
      } else {
        // 如果没有剩余内容，将第一张图片重新作为Markdown内容
        // 确保它能被MarkdownRenderer正确渲染
        const firstImage = images[0];
        setProcessedContent(`![${firstImage.alt}](${firstImage.url})`);
      }
    } else if (
      message.content.includes("![") &&
      message.content.includes("](")
    ) {
      // 如果包含Markdown语法但没有提取出图片，可能是复杂格式
      // 尝试通过添加换行来帮助Markdown解析
      const enhancedContent = message.content.replace(
        /!\[(.*?)\]\((https?:\/\/[^)]+)\)/g,
        (match) => `\n\n${match}\n\n`
      );
      setProcessedContent(enhancedContent);
    } else {
      // 原始内容无需特殊处理
      setProcessedContent(message.content);
    }

    // 清理函数
    return () => {
      processedRef.current = false;
    };
  }, [message.content]);

  // 打开图片预览
  const openImagePreview = (imageUrl: string) => {
    setPreviewImage(imageUrl);
    setIsPreviewOpen(true);
  };

  // 关闭图片预览
  const closeImagePreview = () => {
    setIsPreviewOpen(false);
    setTimeout(() => setPreviewImage(null), 300);
  };

  return (
    <>
      <div
        className={`w-full max-w-full overflow-hidden ${
          isPlaceholder ? "transition-all duration-200 ease-in-out" : ""
        }`}
      >
        {/* 如果有图片，显示图片 */}
        {hasImage && (
          <div className="mb-4">
            <div
              onClick={() => openImagePreview(message.imageUrl!)}
              className="relative inline-block overflow-hidden cursor-pointer transition-all duration-300 group"
            >
              {/* 图片容器 - 毛玻璃效果边框 */}
              <div className="p-[2px] rounded-xl bg-gradient-to-r from-blue-300/30 to-purple-300/30 dark:from-blue-500/20 dark:to-purple-500/20 backdrop-blur-sm shadow-lg hover:shadow-xl transition-all">
                {/* 内部容器 - 深色/浅色适配 */}
                <div className="relative overflow-hidden rounded-[10px] bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm">
                  <img
                    src={message.imageUrl}
                    alt="消息图片"
                    className="max-h-96 max-w-full object-contain group-hover:scale-[1.02] transition-transform duration-300"
                    loading="lazy"
                  />

                  {/* 悬停效果叠加层 */}
                  <div className="absolute inset-0 bg-gradient-to-t from-black/10 to-transparent dark:from-black/20 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>

                  {/* 放大图标 */}
                  <div className="absolute bottom-3 right-3 p-2 rounded-full bg-white/25 dark:bg-black/40 text-gray-700 dark:text-white backdrop-blur-md transform scale-0 group-hover:scale-100 transition-transform duration-300 shadow-lg">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="h-5 w-5"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                      />
                    </svg>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 显示从Markdown提取的图片 */}
        {extractedImages.length > 0 && (
          <div className="mb-4 flex flex-wrap gap-2">
            {extractedImages.map((img, index) => (
              <div
                key={`extracted-img-${index}`}
                onClick={() => openImagePreview(img.url)}
                className="relative inline-block overflow-hidden cursor-pointer transition-all duration-300 group"
              >
                {/* 图片容器 - 特殊样式用于Cirno图片 */}
                <div
                  className={`p-[2px] rounded-xl ${
                    img.url.includes(
                      "cirno-1308416229.cos.ap-chengdu.myqcloud.com"
                    )
                      ? "bg-gradient-to-r from-purple-400/30 to-pink-400/30 dark:from-purple-600/20 dark:to-pink-600/20"
                      : "bg-gradient-to-r from-blue-300/30 to-purple-300/30 dark:from-blue-500/20 dark:to-purple-500/20"
                  } backdrop-blur-sm shadow-lg hover:shadow-xl transition-all`}
                >
                  {/* 内部容器 */}
                  <div className="relative overflow-hidden rounded-[10px] bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm">
                    <img
                      src={img.url}
                      alt={img.alt}
                      className="max-h-96 max-w-full object-contain group-hover:scale-[1.02] transition-transform duration-300"
                      loading="lazy"
                    />

                    {/* Cirno标识 */}
                    {img.url.includes(
                      "cirno-1308416229.cos.ap-chengdu.myqcloud.com"
                    ) && (
                      <div className="absolute top-3 left-3 px-2 py-1 rounded-full bg-purple-500/70 dark:bg-purple-600/70 text-white text-xs backdrop-blur-md shadow-lg">
                        Cirno
                      </div>
                    )}

                    {/* 放大图标 */}
                    <div className="absolute bottom-3 right-3 p-2 rounded-full bg-white/25 dark:bg-black/40 text-gray-700 dark:text-white backdrop-blur-md transform scale-0 group-hover:scale-100 transition-transform duration-300 shadow-lg">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-5 w-5"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                        />
                      </svg>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 显示上传文件的预览和状态 */}
        {hasUploadFiles && message.files && (
          <div className="mb-4">
            <div className="flex flex-wrap gap-4">
              {message.files.map((file, index) => (
                <div key={index} className="relative group">
                  {file.previewUrl ? (
                    <div
                      className="relative cursor-pointer transition-all duration-300"
                      onClick={() => openImagePreview(file.previewUrl!)}
                    >
                      {/* 图片容器 - 毛玻璃效果边框 */}
                      <div className="p-[2px] rounded-xl bg-gradient-to-r from-blue-300/30 to-purple-300/30 dark:from-blue-500/20 dark:to-purple-500/20 backdrop-blur-sm shadow-lg hover:shadow-xl transition-all">
                        {/* 内部容器 - 深色/浅色适配 */}
                        <div className="relative overflow-hidden rounded-[10px] bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm">
                          <img
                            src={file.previewUrl}
                            alt={file.name}
                            className="h-40 w-40 object-cover group-hover:scale-[1.02] transition-transform duration-300"
                          />

                          {/* 悬停效果叠加层 */}
                          <div className="absolute inset-0 bg-gradient-to-t from-black/10 to-transparent dark:from-black/20 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>

                          {/* 放大图标 */}
                          <div className="absolute bottom-3 right-3 p-2 rounded-full bg-white/25 dark:bg-black/40 text-gray-700 dark:text-white backdrop-blur-md transform scale-0 group-hover:scale-100 transition-transform duration-300 shadow-lg">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              className="h-5 w-5"
                              fill="none"
                              viewBox="0 0 24 24"
                              stroke="currentColor"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                              />
                            </svg>
                          </div>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="h-40 w-40 bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-700 dark:to-gray-800 rounded-xl flex items-center justify-center shadow-md backdrop-blur-sm">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-12 w-12 text-gray-400 dark:text-gray-500"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                        />
                      </svg>
                    </div>
                  )}

                  {/* 显示上传状态 */}
                  {file.isUploading && (
                    <div className="absolute inset-0 bg-gray-900/70 dark:bg-gray-900/80 backdrop-blur-sm flex items-center justify-center rounded-xl transition-all">
                      <div className="flex flex-col items-center">
                        <div className="relative">
                          <div className="h-14 w-14 rounded-full border-4 border-gray-300/30 dark:border-gray-600/30 border-t-blue-500 dark:border-t-blue-400 animate-spin"></div>
                          {file.uploadProgress && (
                            <div className="absolute inset-0 flex items-center justify-center">
                              <span className="text-sm font-medium text-white">
                                {file.uploadProgress}%
                              </span>
                            </div>
                          )}
                        </div>
                        <span className="text-sm font-medium text-white mt-3 backdrop-blur-sm bg-black/20 px-3 py-1 rounded-full">
                          上传中...
                        </span>
                      </div>
                    </div>
                  )}

                  {/* 显示上传失败状态 */}
                  {file.error && (
                    <div className="absolute inset-0 bg-red-900/60 dark:bg-red-900/70 backdrop-blur-sm flex items-center justify-center rounded-xl">
                      <div className="flex flex-col items-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className="h-10 w-10 text-white"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                          />
                        </svg>
                        <span className="text-sm font-medium text-white mt-2 backdrop-blur-sm bg-black/20 px-3 py-1 rounded-full">
                          上传失败
                        </span>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 消息内容 - 仅在有内容且不是纯图片链接时显示 */}
        {processedContent && (
          <>
            {isStreaming && isPlaceholder ? (
              <TypewriterEffect content={processedContent} isStreaming={true} />
            ) : allowHtml ? (
              <MarkdownRenderer
                content={processedContent}
                allowHtml={allowHtml}
              />
            ) : (
              <span className="whitespace-pre-wrap">{processedContent}</span>
            )}
          </>
        )}
      </div>

      {/* 图片预览模态框 */}
      {previewImage && (
        <ImagePreview
          imageUrl={previewImage}
          onClose={closeImagePreview}
          isOpen={isPreviewOpen}
        />
      )}
    </>
  );
};

export default MessageContent;
